# Copyright (c) 2008 Chris Moyer
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,-
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import httplib
import urllib2
import xml.sax

from marajo.api.sax_handler import SaxHandler

class MarajoConnection:
    """
    REST API connection interface
    Author: Chris Moyer
    """

    def __init__(self, hostname, username=None, password=None, handler_class=SaxHandler):
        """
        @param hostname: Host to connect to
        @type hostname: str

        @param username: HTTP Basic Auth Username
        @type username: str

        @param password: HTTP Basic Auth Password
        @type password: str
        """
        self.hostname = hostname
        self.username = username
        self.password = password
        self.handler_class = handler_class

        self.opener = None

        self.connect()

    def connect(self):
        """
        Create a connection to the server
        """
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        password_mgr.add_password(None, self.hostname, self.username, self.password)
        handler = urllib2.HTTPBasicAuthHandler(password_mgr)
        self.opener = urllib2.build_opener(handler)

    def _open_path(self, path, protocol="http"):
        """
        Return the response body of the given path, relative to
        the hostname

        @param path: The url to fetch
        @type path: str
        """
        if not self.opener:
            self.connect()
        url = "%s://%s%s" % (protocol, self.hostname, path)
        return self.opener.open(url)

    def get(self, path, filters=[], protocol="http"):
        """
        Fetch the objects from this path.

        @param path: The path to query
        @type path: str

        @param filters: An optional list of filters to query
        @type filters: list

        @param protocol: The protocol (http or https) to use (default http)
        @type protocol: str
        """
        filter_string = ""
        if filters and len(filters) > 0:
            filter_string = "?%s" % ("&".join(filters))
        doc = self._open_path("%s%s" % (path, filter_string), protocol)
        h = self.handler_class()
        xml.sax.parse(doc, h)
        return h
